package day01;

/**
 * @author feng
 * @Date 2021/10/13 9:41
 * 解决线程不安全的问题
 * <p>
 * 1、同步代码块
 * synchronized(同步监视器){
 * 同步监视器，俗称锁
 * 要求，同步代码块必须共用一把锁
 *  在实现runnable接口时了可以考虑this来充当锁
 * }
 *    特别注意:类变量在类加载过程中全局共享
 *
 *   2.同步方法
 */
public class TicketTest extends Thread {
    private static int ticket = 100;
    private static Object  obj = new Object();   //类变量

    public void run() {

            while (true) {
                synchronized (obj) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "票号为" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}


class Test01 {
    public static void main(String[] args) {
        TicketTest t1 = new TicketTest();
        TicketTest t2 = new TicketTest();
        TicketTest t3 = new TicketTest();
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

}
